package com.example.smarthome.ui.masterbedroom;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import android.provider.SyncStateContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.http.HttpHeaders;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.List;
import android.os.Build;
import android.widget.TextView;
import android.widget.Toast;

import com.example.smarthome.R;
import com.google.gson.Gson;

import com.example.smarthome.databinding.FragmentMasterbedroomBinding;
/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MasterbedroomFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MasterbedroomFragment extends Fragment {


    private static final String DeviceID2="1064814621";
    private static final String ApiKey ="1SM9vECD95xFxkRzxivzktUNQko=";
    private static final String key1 ="Led2";
    private static  final String key2="AirSwitch";
    private static  final String key3="Temp";
    TextView data1,data2,data3;
    String value1,value2,value3;
    @RequiresApi(api = Build.VERSION_CODES.M)


    private FragmentMasterbedroomBinding binding;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        MasterbedroomModel masterbedroomModel = new ViewModelProvider(this).get(MasterbedroomModel.class);

        binding = FragmentMasterbedroomBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        data1=binding.switch1;
        data2=binding.switch3;
        data3=binding.textView;

        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            requestPermissions(new String[]{"android.permission.INTERNET"},1);
        }

        Get();





//        binding.textView.setText("35"+"℃");



//        final TextView textView = binding.masterbedroomAir;
//        masterbedroomModel.getText().observe(getViewLifecycleOwner(), textView::setText);

        binding.masterbedroomAir.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent("com.example.activitytest.FENGSHAN_START");
                intent.addCategory("com.example.activitytest.MasterbedroomFENGSHANActivity");
                startActivity(intent);
            }



        });

        binding.switch1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                lightControl();
                if(value1.equals("1")){
                    lightControl("6");
//                    binding.masterbedroomLamp.setText("0");
                }
                if(value1.equals("0")){
                    lightControl("7");
//                    binding.masterbedroomLamp.setText("1");
//                    value1="1";
                }
            }


        });


        binding.switch3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("主卧空调开关", "onClick: ");

                if(value2.equals("1")){
                    lightControl("A");
//                    binding.masterbedroomLamp.setText("0");
                }
                if(value2.equals("0")){
                    lightControl("B");
//                    value1="1";
                }
            }
        });



        binding.textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent("com.example.activitytest.TEMPERATURE_START");
                intent.addCategory("com.example.activitytest.MasterbedroomTEMPERATUREActivity");
                startActivity(intent);
                Log.i("SecondActivity","22");
            }
        });

        return root;
    }

    public void lightControl( String index) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String cmd=index;
                String body=String.format(cmd);
                String url=String.format("http://api.heclouds.com/cmds?device_id="+DeviceID2);
                OkHttpClient client=new OkHttpClient();
                RequestBody requestBody =RequestBody.create(MediaType.parse("application/json;charset=utf-8"),body);
                Request request=new Request.Builder().url(url).header("api-key",ApiKey).post(requestBody).build();
                Call call=client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        String insertStr="请求失败";
                        Log.i("请求失败","22");
//                        Toast.makeText(MasterbedroomFragment.this,insertStr, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                    }
                });
            }
        }).start();
    }

    public void Get(){
        Log.i("diaoyong","diaoyong");
        new Thread(new Runnable() {
            @Override
            public void run () {
                while (true) {
                    try {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder().url("http://api.heclouds.com/devices/" + DeviceID2 + "/datapoints?datastream_id=" + key1).header("api-key", ApiKey).build();
                        Response response=client.newCall(request).execute();
                        String responseData =response.body().string();
                        parseJSONWithGSON(responseData);
                        JsonRootBean app =new Gson().fromJson(responseData,JsonRootBean.class);
                        List<Datastreams> streams=app.getData().getDatastreams();
                        List<Datapoints> points=streams.get(0).getDatapoints();
                        value1=points.get(0).getValue();
//                        Log.e(value1, "value1" );
                        data1.post(new Runnable() {
                            @Override
                            public void run() {
//                                binding.lampTextView.setText(value1);

                                if (value1.equals("0")) {
//                                    binding.masterbedroomLamp.setChecked(false);
                                }
                                if(value1.equals("1")){
//                                    binding.masterbedroomLamp.setChecked(true);

                                }
                            }
                        });
                    }catch (IOException e){
                        e.printStackTrace();
                    }






                    try {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder().url("http://api.heclouds.com/devices/" + DeviceID2+ "/datapoints?datastream_id=" + key2).header("api-key", ApiKey).build();
                        Response response=client.newCall(request).execute();
                        String responseData =response.body().string();
                        parseJSONWithGSON(responseData);
                        JsonRootBean app =new Gson().fromJson(responseData,JsonRootBean.class);
                        List<Datastreams> streams=app.getData().getDatastreams();
                        List<Datapoints> points=streams.get(0).getDatapoints();
                        value2=points.get(0).getValue();

                        data2.post(new Runnable() {
                            @Override
                            public void run() {
//                                binding.fengshanTextView.setText(value2);
                                if (value2.equals("0")) {
//                                    binding.masterbedroomFan.setChecked(false);
                                }
                                if(value2.equals("1")){
//                                    binding.masterbedroomFan.setChecked(true);
                                }
                            }
                        });
                    }catch (IOException e){
                        e.printStackTrace();
                    }

                    try {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder().url("http://api.heclouds.com/devices/" + DeviceID2+ "/datapoints?datastream_id=" + key3).header("api-key", ApiKey).build();
                        Response response=client.newCall(request).execute();
                        String responseData =response.body().string();
                        parseJSONWithGSON(responseData);
                        JsonRootBean app =new Gson().fromJson(responseData,JsonRootBean.class);
                        List<Datastreams> streams=app.getData().getDatastreams();
                        List<Datapoints> points=streams.get(0).getDatapoints();
                        value3=points.get(0).getValue();

                        value3=value3+"℃";
                        data3.post(new Runnable() {
                            @Override
                            public void run() {
//                                Log.i("textView","22");
                                binding.textView.setText(value3);
//                                if(x<y)
//                                {
//                                    Log.i("textView","22");
//                                    lightControl("5");
//                                    x=30;
//                                }

                            }
                        });
                    }catch (IOException e){
                        e.printStackTrace();
                    }

                }
            }
        }).start();


    }
    private void parseJSONWithGSON(String jsonData){
        JsonRootBean app =new Gson().fromJson(jsonData,JsonRootBean.class);
        List<Datastreams> streams =app.getData().getDatastreams();
        List<Datapoints> points =streams.get(0).getDatapoints();
        int count=app.getData().getCount();
        for (int i=0;i< points.size();i++){
            String time=points.get(i).getAt();
            String value =points.get(i).getValue();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}